<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList" :empty-view-center="false" :hide-no-more-by-limit="10" :auto="false">
		<template v-slot:top>
			<!-- <view class="searchBox">
				<uni-search-bar
					placeholder="搜索商品名称、装车地点、卸车地点"
					@confirm="search"
					v-model="searchValue"
					@cancel="cancel"
					@clear="clear"
					@input="(e) => queryList(null, null, e)"
				></uni-search-bar>
			</view> -->
		</template>
		<view class="box">
			<!-- 关注的行业 搜索 -->
			<view
				:class="['container', index + 1 != dataList.length && 'conLines', item?.dataChangeMsgs?.length && 'notify']"
				v-for="(item, index) in dataList"
				:key="index"
				@click="navTo(`/pages/driver/index/orderDetails/orderDetails`, { item })"
			>
				<u-alert-tips v-if="item?.dataChangeMsgs?.length" type="warning" title="" :description="descriptionGet(item?.dataChangeMsgs)"></u-alert-tips>
				<view class="shopType">
					<text class="circle">{{ index + 1 }}</text>
					<text class="shopName">
						{{ item.commodityName }}
					</text>
					<u-tag :text="item.vehicleNo" type="primary" size="mini" mode="dark" />
					<view class="status" v-if="item.vehicleState == 1">未到厂</view>
					<view class="status" v-if="item.vehicleState == 2">已到厂</view>
					<view class="status" v-if="item.vehicleState == 3">已装车</view>
					<view class="status" v-if="item.vehicleState == 4">已卸车</view>
				</view>
				<view class="con">
					<view class="item">
						<text class="type">装车日期:</text>
						<text>{{ item.loadingTime || '--' }}</text>
					</view>
					<view class="item">
						<text class="type">预装吨位:</text>
						<text>{{ item.tonnage || '--' }}</text>
					</view>
					<!--<view class="item">
						<text class="type">已填车数:</text> <text>67 <text class="unit">辆</text> </text>
					</view> -->
					<view class="item">
						<text class="type">实际装车吨位:</text>
						<text>{{ item.loadingTonnage || '--' }}</text>
					</view>
					<view class="item">
						<text class="type">实际卸车吨位:</text>
						<text>{{ item.unloadTonnage || '--' }}</text>
					</view>
					<view class="item">
						<text class="type">装车地点:</text>
						<view class="rightBox">
							<text class="text">{{ item.loadingAddress || '--' }}</text>
							<image class="img" src="/static/area.png" mode="widthFix"></image>
						</view>
					</view>
					<view class="item">
						<text class="type">卸车地点:</text>
						<view class="rightBox">
							<text class="text">{{ item.unloadAddress || '--' }}</text>
							<image class="img" src="/static/area.png" mode="widthFix"></image>
						</view>
					</view>
				</view>
				<view class="btns">
					<u-button type="primary" size="mini" @click="confirmation(item)" v-if="item.dataChangeMsgs?.length">确认通知</u-button>
					<u-button type="primary" size="mini" @click="navTo(`/pages/driver/index/orderDetails/orderDetails`, { item })" v-if="item.vehicleState == 2">装车榜单</u-button>
					<u-button type="primary" size="mini" @click="navTo(`/pages/driver/index/orderDetails/orderDetails`, { item })" v-if="item.vehicleState == 3">卸车榜单</u-button>
					<u-button type="primary" size="mini" v-if="item.vehicleState == 1" @click="confirm(item)">确认到厂</u-button>
				</view>
			</view>
		</view>
	</z-paging>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { onLoad, onUnload, onShow, onHide, onReady } from '@dcloudio/uni-app';
import { navTo, setLoadingToast, setToast } from '@/common/utils';
import { factoryConfirm, getList } from '@/api/drive';
import { confirmNotify } from '../../../../api/logisitcsCompany';

const paging = ref(null);
const firstLoaded = ref(false);
const dataList = ref([]);
const search = ref('');

const Props = defineProps({
	state: Number || String,
	item: Object,
	current: Number,
	swiperCurrent: Number
});

watch(
	() => Props.current,
	(newVal) => {
		// console.log('newVal ============> ', newVal);
		if (newVal === Props.swiperCurrent) {
			//懒加载，当滑动到当前的item时，才去加载
			if (!firstLoaded.value || !dataList.value.length) {
				firstLoaded.value = true;
				setTimeout(() => {
					paging.value.reload();
				}, 100);
			}
		}
	},
	{ immediate: true }
);

const cache = {
	salesmanType: 8
};

const queryList = (pageNumber, pageSize, filterText) => {
	if (pageNumber) {
		cache.pageNumber = pageNumber;
		cache.pageSize = pageSize;
		cache.state = Props.state;
	} else {
		cache.filterText = filterText;
	}
	getList(cache).then((res) => {
		paging.value.complete(res.data.rows);
	});
};

const descriptionGet = (data) => {
	let str = '';
	const changeData = {};
	data.forEach((notify) => {
		const changeMap = JSON.parse(notify.content);
		changeMap.forEach(({ fieldName, newValue }) => {
			switch (fieldName) {
				case '装车地点':
					changeData[fieldName] = `装车地点发生改变，新装车地点为:${newValue}`;
					break;
				case '卸车地点':
					changeData[fieldName] = `卸车地点发生改变，新卸货地址为:${newValue}`;
					break;
				default:
					break;
			}
		});
	});

	for (let key in changeData) {
		str += changeData[key] + '。';
	}

	return str + '确认无误请点击下方`确认通知`确认收到。';
	// 当前车辆卸车地点发生改变，新卸货地址为:河南省郑州市，运价为:780，确认无误请点击下方`确认通知`确认收到。
};

// 确认到厂
const confirm = ({ id }) => {
	uni.showModal({
		title: '到厂确认',
		content: '请确认车辆已到厂？',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确认',
		success: (res) => {
			if (res.confirm) {
				setLoadingToast('处理中...');
				factoryConfirm({ id }).then((res) => {
					if (res.data !== false) {
						setToast('到厂已确认');
						updateVehicleState(id, 2);
					}
					uni.hideLoading();
				});
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

const updateVehicleState = (id, vehicleState) => {
	dataList.value = dataList.value.map((v) => {
		if (v.id === id) {
			v.vehicleState = vehicleState;
		}
		return v;
	});
};

// 确认通知
const confirmation = (data) => {
	console.log('data ===> ', data);
	const dataIds = data.map((v) => v.id);
	console.log('dataIds ===》 ', dataIds);
	uni.showModal({
		title: '通知',
		content: '请确认信息已核实无误。',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确认',
		success: async (res) => {
			if (res.confirm) {
				setLoadingToast('操作中...');
				try {
					dataIds.forEach(async (id) => await confirmNotify({ id }));
					uni.hideLoading();
					queryList();
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading();
				}
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

const uniOn = (id) => {
	const uniData = dataList.value.find((v) => v.id === id);
	if (uniData) {
		// 如果是已装车 再次修改的时候 不更改本页内容
		if ([3, 4].includes(+uniData.vehicleState)) return;
		updateVehicleState(id, 3);
	}
};

onLoad(() => {
	uni.$on('ok', uniOn);
});

onUnload(() => {
	uni.$off('ok', uniOn);
});
</script>

<style scoped lang="scss">
.conLines {
	border-bottom: 6rpx solid #f8f8f8;
}

.searchBox {
	padding: 10rpx;
	// border: 1rpx solid red;
}

.container {
	padding: 20rpx 30rpx;

	.shopType {
		font-size: 28rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 0;
		// border: 1rpx solid red;

		.shopName {
			margin-right: 10px;
		}

		.status {
			margin-left: auto;
			color: #51a9ec;
		}

		.circle {
			margin-right: 10rpx;
			font-size: 24rpx;
			display: flex;
			width: 40rpx;
			height: 40rpx;
			background-color: #51a9ec;
			justify-content: center;
			align-items: center;
			border-radius: 50%;
			color: #fff;
		}
	}

	.btns {
		padding: 15rpx 0;
		text-align: right;
		// border: 1rpx solid red;

		& > * {
			margin-left: 15rpx;
		}
	}

	.con {
		display: flex;
		flex-direction: column;
		// border: 1rpx solid red;
		// background-color: #fff;

		.conRow {
			display: flex;
		}

		.item {
			flex: 1;
			padding: 10rpx 0;
			// border: 1px solid red;
			display: flex;
			justify-content: space-between;

			.type {
				color: #bdbdbd;
				font-size: 26rpx;
			}

			.unit {
				font-size: 23rpx;
			}

			.rightBox {
				display: flex;
				align-items: center;

				.text {
					font-weight: 500;
					font-size: 26rpx;
					width: 500rpx;
					text-align: right;
				}

				.img {
					width: 35rpx;
					height: 35rpx;
					margin-left: 10rpx;
				}
			}
		}
	}
}

.notify {
	background: #ffffb3;
	color: #000;

	.type {
		color: #606060 !important;
	}
}
</style>
